//
//  YHWebViewController.swift
//  SwiftProject
//
//  Created by qindong on 2021/4/6.
//

import UIKit
import WebKit

enum WebViewType {
    case local(_ path : String?, _ type : String?)
    case network(_ url : String?)
    case htmlString(_ htmlString : String?)
}

class BaseWebViewController: BaseViewController, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler {
    lazy var webView = WKWebView(frame: .zero, configuration: configuration)
    let progressView = UIProgressView()
    let configuration = WKWebViewConfiguration()

    var webViewType : WebViewType = .network("")
    
    convenience init(_ webViewType : WebViewType = .network("https://www.baidu.com")) {
        self.init()
        self.webViewType = webViewType
    }
    
    private init() {
        super.init(nibName:nil, bundle:nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBarType = .light
        CustomRelay.manager.loginSuccessPublishRelay.subscribe (onNext: { [unowned self] _ in
            self.webView.reloadFromOrigin()
        }).disposed(by: rx.disposeBag)
    }
    
    override func initSubviews() {
        super.initSubviews()

        let userController = WKUserContentController()
//        userController.add(self, name: "needToLogin")
        switch webViewType {
        case .local:
            // 解决加载本地html可能出现字体小的问题
            let jScript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"
            let wkUScript = WKUserScript(source: jScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
            userController.addUserScript(wkUScript)
        default:
            break
        }
        configuration.userContentController = userController

        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.allowsBackForwardNavigationGestures = true
        view.addSubview(webView)
        
        switch webViewType {
        case .network(let url):
            if let url = url {
                webView.load(URLRequest(url: URL(string: url)!))
            }
        case .local(let path, let type):
            if let path = path, let type = type {
                let url = URL(fileURLWithPath: Bundle.main.path(forResource: path, ofType: type)!)
                let request = URLRequest(url: url)
                webView.load(request)
            }
        case .htmlString(let htmlString):
            if let htmlString = htmlString {
                webView.loadHTMLString(htmlString, baseURL: nil)
            }
        }
        
        webView.snp.makeConstraints { make in
            make.edges.equalTo(view)
        }
        
        progressView.frame = CGRect(x: 0, y: NavigationContentTop, width: SCREEN_WIDTH, height: 2)
        progressView.progressTintColor = .colorMain
        view.addSubview(progressView)
        
        webView.rx.observe(String.self, "title").subscribe (onNext: { [unowned self] title in
            self.title = title
        }).disposed(by: rx.disposeBag)
        
        webView.rx.observe(Double.self, "estimatedProgress").subscribe (onNext: { [unowned self] estimatedProgress in
            if estimatedProgress == nil { return }
            self.progressView.progress = Float(estimatedProgress!)
            if estimatedProgress == 1 {
                UIView.animate(withDuration: 0.25, delay: 0.3, options: UIView.AnimationOptions.curveEaseOut) {
                    self.progressView.transform = CGAffineTransform.init(scaleX: 1.0, y: 1.4)
                } completion: { (finished) in
                    self.progressView.isHidden  = true
                }
            }
        }).disposed(by: rx.disposeBag)
        
        webView.rx.didStartLoad.subscribe (onNext: { [unowned self] _ in
            self.progressView.isHidden = false
            self.progressView.transform = CGAffineTransform(scaleX: 1.0, y: 1.5)
            self.view.bringSubviewToFront(self.progressView)
        }).disposed(by: rx.disposeBag)
        
        webView.rx.didFinishLoad.subscribe ({ [unowned self] _ in
            self.checkGoBack()
            
        }).disposed(by: rx.disposeBag)
        
        webView.rx.didFailLoad.subscribe (onNext: { [unowned self] (_, _) in
            self.checkGoBack()
        }).disposed(by: rx.disposeBag)
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {

    }
    
    @objc override func baseBackBtnAction(btn: UIButton) {
        if webView.canGoBack {
            webView.goBack()
        } else {
            navigationController?.qmui_popViewController(animated: true, completion: nil)
        }
    }
    
    @objc func closeBtnAction() {
        navigationController?.qmui_popViewController(animated: true, completion: nil)
    }
    
    func checkGoBack() {
        if webView.canGoBack {
            navigationItem.leftBarButtonItems = leftButtons()
        } else {
            navigationItem.leftBarButtonItem = backBtn()
        }
    }
    
    func leftButtons() -> [UIBarButtonItem] {
        let closeButton = closeBtn()
        closeButton.action = #selector(closeBtnAction)
        return [backBtn(), closeButton]
    }
    
    override func customNavigationBarTransitionKey() -> String? {
        "web"
    }
}
